package com.yazi.mxz.common.service.impl;

import java.util.List;

import javax.annotation.Resource;

import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyIllegalArgumentException;
import com.myframework.smhj.common.exception.MyNoPermissionException;
import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yazi.mxz.common.ComSetting;
import com.yazi.mxz.common.db.dao.FeedbackDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Feedback;
import com.yazi.mxz.common.entity.enums.SettingId;
import com.yazi.mxz.common.service.FeedbackService;

@Service("feedbackService")
public class FeedbackServiceImpl extends BasicService<Feedback> implements FeedbackService {
	private static Logger log = LoggerFactory.getLogger(FeedbackServiceImpl.class);
	
	@Resource
	FeedbackDao feedbackDao;
	
	@Override
	protected Dao<Feedback> getDao() {
		return feedbackDao;
	}
	
	@Override
	public Feedback add(Feedback feedback) throws MyException {
		log.debug("add：");
		if (null == feedback.getContent() || null == feedback.getIp()) {
			throw new MyIllegalArgumentException();
		}
		// feedback for search
		Feedback feedback4s = new Feedback();
		feedback4s.setIp(feedback.getIp());
		List<Feedback> list = feedbackDao.listByExample(feedback4s, new Searching()).getList();
		// 与上次提交的时间间隔小指定的时间
		if (list.size() > 0 
				&& list.get(0).getAddTime() > (DateUtil.getTimeStamp() - ComSetting.getInteger(SettingId.FEEDBACK_LAG) * 6e4)) {
			throw new MyNoPermissionException("操作过于频繁");
		}
		
		feedback = ValueFactory.validate(feedback);
		feedback.setAddTime(DateUtil.getTimeStamp());
		feedback.setFeedbackId(null);

		return feedbackDao.persist(feedback);
	}

}
